package com.doodle.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.doodle.common.data.ResultModel;

import org.json.JSONObject;

public class JSONUtils {

	private static ResultModel<Object> parseResultModel(String jsonStr) {
		TypeReference<ResultModel<Object>> typeRef = new TypeReference<ResultModel<Object>>() {};
		try {
			return JSON.parseObject(jsonStr, typeRef);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static <T> ResultModel<T> parseResultModel(String jsonStr, TypeReference<ResultModel<T>> typeRef) {
		try {
			return JSON.parseObject(jsonStr, typeRef);
		} catch (JSONException e) {
			ResultModel<Object> retryResult = parseResultModel(jsonStr);
			if (retryResult != null) {
				ResultModel<T> result = new ResultModel<T>();
				result.setReturnCode(retryResult.getReturnCode());
				result.setReturnMessage(retryResult.getReturnMessage());
				result.setReturnUrl(retryResult.getReturnUrl());
				result.setReturnValue(null);
				return result;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static <T> T parseJSONObject(String jsonStr, TypeReference<T> typeRef) {
		try {
			return JSON.parseObject(jsonStr, typeRef);
		} catch (JSONException e) {
			if ("unclosed string : '".equals(e.getMessage())) {
				jsonStr = jsonStr.replace("\\'", "'");
				return JSON.parseObject(jsonStr, typeRef);
			} else {
				e.printStackTrace();
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取json内容中指定tag下的String
	 * @param jsonStr
	 * @param tag 顶层tag
	 * @return
	 */
	public static String getTagString(String jsonStr, String tag) {
		try {
			JSONObject obj = new JSONObject(jsonStr);
			return obj.getString(tag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
